package com.jcfk.system.service;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.common.core.context.SpringContextUtils;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.domain.dto.MailInfoDTO;
import com.jcfk.system.domain.model.SendMsgModel;
import com.jcfk.system.domain.po.SysMessageSendRecord;
import com.jcfk.system.domain.po.SysMessageSendRecordDetails;
import com.jcfk.system.domain.po.SysMessageSendUser;
import com.jcfk.system.utils.mail.MailHelper;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 发送站内消息
 */
@Component("emailMessageService")
public class EmailMessageService {
    private static MailHelper mailHelper;

    private static SysMessageSendUserService sysMessageSendUserService;


    private static SysMessageSendRecordService sysMessageSendRecordService;


    private static SysMessageSendRecordDetailsService sysMessageSendRecordDetailsService;

    // 使用静态代码块及SpringContextUtils获取对象
    static {
        mailHelper = SpringContextUtils.getBean(MailHelper.class);
        sysMessageSendUserService = SpringContextUtils.getBean(SysMessageSendUserService.class);
        sysMessageSendRecordService = SpringContextUtils.getBean(SysMessageSendRecordService.class);
        sysMessageSendRecordDetailsService = SpringContextUtils.getBean(SysMessageSendRecordDetailsService.class);
    }

    /**
     * 发送邮件
     */
    public void emailMessage(SendMsgModel message, SysMessageSendRecord record) {

        // 接收人去重
        message.setReceiveUserIds(message.getReceiveUserIds().stream().distinct().collect(Collectors.toList()));
        message.setReceivePhones(message.getReceivePhones().stream().distinct().collect(Collectors.toList()));
        message.setReceiveEmails(message.getReceiveEmails().stream().distinct().collect(Collectors.toList()));

        // 接收人手机号赋值
        if (message.getReceiveEmails() == null || message.getReceiveEmails().size() <= 0) {
            QueryWrapper<SysMessageSendUser> sysMessageSendUserQueryWrapper = new QueryWrapper<>();
            sysMessageSendUserQueryWrapper.lambda().eq(SysMessageSendUser::getTempleId, record.getTempleId()).eq(SysMessageSendUser::getDeleted, 0).eq(SysMessageSendUser::getType, 3);
            List<SysMessageSendUser> list = sysMessageSendUserService.list(sysMessageSendUserQueryWrapper);
            List<String> emails = new ArrayList<>();
            for (SysMessageSendUser user : list) {
                if (!StringUtils.isEmpty(user.getEmail())) emails.add(user.getEmail());
            }
            message.getReceiveEmails().addAll(emails);
        }


        MailInfoDTO mailInfo = new MailInfoDTO();
        mailInfo.setToMails(message.getReceiveEmails());
        mailInfo.setSubject(message.getTitle());
        mailInfo.setText(message.getMsgBody());
        mailInfo.setFiles(message.getFiles());
        mailInfo.setMessageLevel(message.getMessageLevel());
        mailInfo.setCcMails(message.getCcMails());

        /**
         * 邮箱发送
         * */
        RetResult retResult = mailHelper.sendEmail(mailInfo);

        List<SysMessageSendRecordDetails> emailDetails = new ArrayList<>();
        List<String> errmials = new ArrayList<>();
        // 发送失败
        if (retResult.getCode() != 200) {
            record.setMessageStatus(2);
            record.setErrMessage(retResult.getMessage());
        } else {
            errmials = (List<String>) retResult.getData();
            // 异常
            if (errmials.size() > 0 && errmials.size() != message.getReceiveEmails().size()) {
                record.setMessageStatus(3);
            }
            // 全部错误
            if (errmials.size() > 0 && errmials.size() == message.getReceiveEmails().size()) {
                record.setMessageStatus(2);
            }
        }

        // 发送记录入库
        for (String email : message.getReceiveEmails()) {
            SysMessageSendRecordDetails details = new SysMessageSendRecordDetails();
            details.setEmail(email);
            details.setContent(message.getMsgBody());
            details.setMessageId(record.getId());
            details.setTitle(record.getTitle());
            if (retResult.getCode() != 200) {
                details.setMessageStatus("2");
            } else {
                if (errmials.contains(email)) {
                    details.setMessageStatus("2");
                }
            }
            details.setCreateTime(new Date());
            details.setCreatedUserId(record.getCreatedUserId());
            details.setCreatedUserName(record.getCreatedUserName());
            emailDetails.add(details);
        }


        if (emailDetails.size() > 0) sysMessageSendRecordDetailsService.saveBigBatch(emailDetails);
        sysMessageSendRecordService.updateById(record);


    }

}
